<template>
  <div class="app-container">
    <el-card class="table-wrapper">
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增规则</el-button>
      </div>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="prefix" label="卡号前缀" width="120" />
        <el-table-column prop="length" label="卡号长度" width="120" />
        <el-table-column prop="type" label="卡片类型" width="120">
          <template #default="scope">
            {{ scope.row.type === 'primary' ? '主卡' : '子卡' }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="规则说明" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              :type="scope.row.status ? 'danger' : 'success'"
              link
              @click="handleStatus(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增规则' : '编辑规则'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="卡号前缀" prop="prefix">
          <el-input v-model="form.prefix" placeholder="请输入卡号前缀" />
        </el-form-item>
        <el-form-item label="卡号长度" prop="length">
          <el-input-number v-model="form.length" :min="8" :max="20" />
        </el-form-item>
        <el-form-item label="卡片类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="primary">主卡</el-radio>
            <el-radio label="sub">子卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规则说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入规则说明"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

// 表单数据
const form = reactive({
  prefix: '',
  length: 16,
  type: 'primary',
  description: '',
  status: 1
})

// 表单校验规则
const rules = {
  prefix: [
    { required: true, message: '请输入卡号前缀', trigger: 'blur' },
    { pattern: /^[A-Z0-9]+$/, message: '前缀只能包含大写字母和数字', trigger: 'blur' }
  ],
  length: [
    { required: true, message: '请输入卡号长度', trigger: 'blur' },
    { type: 'number', min: 8, max: 20, message: '长度必须在8-20之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择卡片类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入规则说明', trigger: 'blur' }
  ]
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/admin/black-card/rule/list', {
      params: queryParams
    })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取列表失败：', error)
  }
  loading.value = false
}

// 分页
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = key === 'length' ? 16 : key === 'type' ? 'primary' : key === 'status' ? 1 : ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await request.post('/black-card/rule', form)
          ElMessage.success('新增成功')
        } else {
          await request.put(`/black-card/rule/${form.id}`, form)
          ElMessage.success('编辑成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败：', error)
        ElMessage.error('提交失败')
      }
    }
  })
}

// 更改状态
const handleStatus = (row) => {
  const statusText = row.status ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确认要${statusText}该规则吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await request.put(`/black-card/rule/${row.id}/status`, {
        status: row.status ? 0 : 1
      })
      ElMessage.success(res.message)
      getList()
    } catch (error) {
      console.error('更改状态失败：', error)
    }
  }).catch(() => {})
}

// 初始化
getList()
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .table-wrapper {
    .toolbar {
      margin-bottom: 20px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 